#!/bin/sh
# pyshell by Filippo Squillace  
# (great update 16-12-2009 date of my last exam in UNICAL :)
# (update 21-07-2010 one of my last days in Valencia §:(  )
# (update 07-01-2012 ending the thesis in Valencia)
# (update 29-01-2012 continue ending thesis in Valencia)
# Usage: source pyshell OR bash --rcfile pyshell


# If not running interactively, don't do anything
[ -z "$PS1" ] && return
[[ $- != *i* ]] && return


if [ "${BASH_ARGV}" = "" ]; then
    echo "Error the correct usage is: source $0 OR bash --rcfile $0"
    exit 128
fi


# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"


# Possible choices:
#umask   file mode   directory mode
#0022    -rw-r--r--  drwxr-xr-x
#0077    -rw-------  drwx------
umask 0077



######################### INSTALLATION STEP ###########################

THIS_FILE=`basename ${BASH_ARGV[0]}`
export PYSHELL_ROOT=$(readlink -f "${BASH_ARGV[0]%/*}/")
export PYSHELL_HOME=~/.config/pyshell
export PYSHELL_TEMPORARY=$PYSHELL_HOME/tmp/`tty`

# Get functions from misc.sh
source $PYSHELL_ROOT/lib/misc.sh


if [ -e $PYSHELL_HOME ]
then
    # Check updates
    svn info $PYSHELL_ROOT &> /dev/null
    if [ "$?" = "0"  ]
    then
        svn update $PYSHELL_ROOT &> /dev/null &
    fi
    
    source $PYSHELL_HOME/pyshellrc
else

    # Sourcing bash config.
    apply "source $PYSHELL_ROOT/pyshell" $HOME/.bashrc

    # Sourcing vim config.
    apply "source $PYSHELL_ROOT/etc/vimrc" $HOME/.vimrc

    # Sourcing input config
    apply "\$include $PYSHELL_ROOT/etc/inputrc" $HOME/.inputrc

    # Sourcing commands.py ranger config
    apply "exec(open('$PYSHELL_ROOT/etc/ranger/commands.py').read())" $HOME/.config/ranger/commands.py


    echo "Creating ~/.config/pyshell directory ..."
    mkdir -p $PYSHELL_HOME/bkp
    mkdir -p $PYSHELL_HOME/etc
    
    echo "You can put now your own script code in $PYSHELL_HOME/pyshellrc... ;)"
    echo "#!/bin/bash" > $PYSHELL_HOME/pyshellrc
    echo "#This script is used to execute anything you want. " >> $PYSHELL_HOME/pyshellrc
    echo "# Uncomment and type your Dropbox/Ubuntu One home if it's different from ~/Dropbox/:" >> $PYSHELL_HOME/pyshellrc
    echo "#export SYNC_HOME=~/Dropbox/" >> $PYSHELL_HOME/pyshellrc
    chmod +x $PYSHELL_HOME/pyshellrc
    
    
fi

mkdir -p $PYSHELL_TEMPORARY

#####################################################################################################

# Shows informations system
#(uname -m && cat /etc/*release) | xargs

export SYNC_HOME=~/Dropbox/

# Variables environment for logging system
export PYSHELL_DEBUG=0

export PYTHONPATH=$PYTHONPATH:$PYSHELL_ROOT/lib

# Then define the PATH variable
PATH=${PYSHELL_ROOT}/bin:${PATH}


# Then define the HIST variables
export HISTFILESIZE=100000
export HISTSIZE=100000
export HISTIGNORE="&:l[las]:[bf]g:l:a:j:f:b:e"
export HISTCONTROL=erasedups:ignorespace

##### Bash options #######
shopt -s cdspell
shopt -s autocd
shopt -s dirspell
# append to the history file, don't overwrite it
shopt -s histappend
# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize


#### The aliases(sqoox85)

# Mini-aliases :)
alias j="jobs"
alias f="fg"
alias b="bg"
alias q="exit"
alias ls="ls --color=auto"
alias l="ls -h"
alias a="ls -ha"


alias ll="l -l"
alias la="a -l"

alias share="cd ${PYSHELL_ROOT}/share"
alias home="cd ${HOME}"
alias etc="cd ${PYSHELL_ROOT}/etc"
alias bin="cd ${PYSHELL_ROOT}/bin"

# Allows to keep aliases in sudo
alias sudo="sudo "
#alias sudo="sudo -E"    # Useful to keep variables environment when you are root

alias goo="ping www.google.it"
alias isconnect="python -c \"import util.net;print(util.net.is_connect())\""

alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'

# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.
if [ -f ~/.bash_aliases ]; then
        . ~/.bash_aliases
fi

# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
        . /etc/bash_completion
fi


# Trash command
function trash(){
    mkdir -p $PYSHELL_TEMPORARY

    if [ -z "$1" ] || [ "$1" = -s ] || [ "$1" = --show ]
    then
        ll -a $PYSHELL_TEMPORARY
    elif [ "$1" = -e ] || [ "$1" = --empty ]
    then
        rm -rf $PYSHELL_TEMPORARY/*
    elif [ "$1" = -h ] || [ "$1" = --help ]
    then
        echo "Usage:"
        echo -e "trash FILE1 FILE2 ...\t\tMoves to trash the files"
        echo -e "trash [-s || --show]\t\tShows the trash"
        echo -e "trash [-e || --empty]\t\tEmpties the trash"
        echo -e "trash [-h || --help]\t\tDisplays this"
    else
        mv -b -f -t $PYSHELL_TEMPORARY $@
    fi

}

# cd to last path after exit
# This functionallows to change the directory 
# to the last visited one after ranger quits.
# You can always type "cd -" to go back
# to the original one.
function ranger(){
    tempfile='/tmp/chosendir'
    /usr/bin/ranger --choosedir="$tempfile" "${@:-$(pwd)}"
    test -f "$tempfile" &&
    if [ "$(cat -- "$tempfile")" != "$(echo -n `pwd`)" ]; then
        echo $(cat "$tempfile")
        builtin cd -- "$(cat "$tempfile")"
    fi
    rm -f -- "$tempfile"
}

# This binds Ctrl-O to ranger:
bind '"\C-o":"\C-u ranger\C-m"'


# Create a sync with Dropbox/Ubuntu One folder using 
# absolute path to maintain the same structure
function sync() {
    if [ "$1" = -h ] || [ "$1" = --help ]
    then
        echo "Usage:"
        echo -e "sync [--exclude=PATTERN] FILE1 FILE2 ...\tSync files or directories"
        echo -e "\t\texcluding what mathces with PATTERN"
        echo -e "trash [-h || --help]\t\tDisplays this"
        return 0
    fi

    # introduce --exclude option
    exc_opt=""
    for ((i=1; i<=$#;i++))
    do
        if [[ "${!i}" != *--exclude* ]]
        then
            break
        else
            exc_opt="${exc_opt} ${!i}"
        fi
    done

    #for var in "$@" #Another solution
    for ((j=$i;j<=$#;j++))
    do
        # Rsync Options:
        # -c:     Enable checksum
        # -a:     Preserve the attibutes of the files.
        # -v:     Verbose.
        # -z:     Enables the compression.
        # -u:     Update files.
        # -r:     Recursive.
        # -E:     Preserve Executability.
        # -h:     Human readable.
        # -n:     Simulate.
        # -R:     Relative (include implied directories).
        # -C:     Exclude CVS.
        # --exclude=.svn

        rsync -R -C --exclude=.svn ${exc_opt} -uhzravE --delete $(readlink -f ${!j}) $SYNC_HOME 
        
        # The following solution doesn't manage deletion of files in the destination
        #cp -v -a --parents -u -r --target-directory $SYNC_HOME/ $(readlink -f $var)
    done

}


# This function integrate cd and cd2 in the same command
function cd() {
    if [ -z "$1" ] 
    then
	$PYSHELL_ROOT/bin/cd2
    elif [ "$1" = -g ]
    then
        builtin cd `$PYSHELL_ROOT/bin/cd2 -p $2`
    elif [ "$1" = -a ] || [ "$1" = --add ] || [ "$1" = -r ] || [ "$1" = --remove ] \
	|| [ "$1" = -h ] || [ "$1" = --help ] || [ "$1" = -p ] || [ "$1" = --print ]
    then
        $PYSHELL_ROOT/bin/cd2 $1 $2
    else
	builtin cd $1
    fi
}

####

#>>> Here manage the prompt(sqoox85)
prompt="\[\033[01;31m\][\[\033[1;32m\]\t \[\033[1;33m\]\j \[\033[01;31m\]\u@\h \[\033[01;34m\]\W \[\033[01;35m\]\$\[\033[01;31m\]]> \[\033[00m\]"
if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
    # We have color support; assume it's compliant with Ecma-48
    # (ISO/IEC-6429). (Lack of such support is extremely rare, and such
    # a case would tend to support setf rather than setaf.)
    PS1=$prompt
fi

case ${TERM} in
  xterm*|rxvt*|Eterm|aterm|kterm|gnome*)
    PS1=$prompt
    PROMPT_COMMAND=${PROMPT_COMMAND:+$PROMPT_COMMAND; }'printf "\033]0;%s@%s:%s\007" "${USER}" "${HOSTNAME%%.*}" "${PWD/#$HOME/~}"'
    ;;

  screen)
    PS1=$prompt
    PROMPT_COMMAND=${PROMPT_COMMAND:+$PROMPT_COMMAND; }'printf "\033_%s@%s:%s\033\\" "${USER}" "${HOSTNAME%%.*}" "${PWD/#$HOME/~}"'
    ;;

  *)
    ;;
esac

unset prompt
#>>>

#*** Handle to clean temp directory
trap "/bin/rm -fr $PYSHELL_TEMPORARY" QUIT EXIT ABRT KILL TERM


#******* Script to trap USR1 signal in order to handle changing directory
function sigusr2()
{ 
  source $PYSHELL_TEMPORARY/new_cmd

}

trap "sigusr2" USR2       # catch -USR2 signal



